package com.ipan.weixin.msg.general;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;


/**
 * 文本消息
 * 
 * @author iPan
 * @version 2013-12-23
 */
public class TextMsg extends PlainMsg {
	
	/** serialVersionUID */
	private static final long serialVersionUID = 2257567566083522721L;
	
	/** 文本消息内容（必须） */
	protected String content;
	
	public TextMsg() {
		super(TransportType.RECEIVE_AND_REPLY);
	}
	
	public TextMsg(Document doc) {
		this();
		fromXml(doc);
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	@Override
	public void fromXml(Document doc) {
		if (doc == null) {
			return ;
		}
		
		super.fromXml(doc);
		Element root = doc.getRootElement();
		this.content = root.elementTextTrim(EL_CONTENT);
	}

	@Override
	public String toXml(boolean nonEmpty) {
		StringBuilder buf = new StringBuilder("<xml>");
		buf.append(super.toXml(nonEmpty));
		buf.append(wrapElementHead(EL_MSG_TYPE)).append(TYPE_TEXT).append(wrapElementEnd(EL_MSG_TYPE));
		if (nonEmpty) {
			if (StringUtils.isNotEmpty(this.content)) {
				buf.append(wrapElementHead(EL_CONTENT)).append(this.content).append(wrapElementEnd(EL_CONTENT));
			}
		} else {
			buf.append(wrapElementHead(EL_CONTENT)).append(getStringValue(this.content)).append(wrapElementEnd(EL_CONTENT));
		}
		return buf.append("</xml>").toString();
	}
}

/*---------------------------------------------
接收：
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName> 
<CreateTime>1348831860</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[this is a test]]></Content>
<MsgId>1234567890123456</MsgId>
</xml>

回复：
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[你好]]></Content>
</xml>
--------------------------------------------*/